package com.cli.spring_session_demo.exceptions;

import com.cli.spring_session_demo.error.ErrorCode;
import com.cli.spring_session_demo.error.ErrorResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by work on 2017/5/31.
 * exception wrapper for transforming custom exception to json
 */
public class APIException extends Exception {
    private static final Logger logger = LoggerFactory.getLogger(APIException.class);

    protected ErrorCode errorCode;
    protected String message;

    /**
     * transform APIException to json string
     *
     * @return json string
     */
    public String toJSON() {
        ErrorResponse response = new ErrorResponse(errorCode, message);
        logger.debug(response.toString());

        String res = "APIException";
        ObjectMapper mapper = new ObjectMapper();
        try {
            res = mapper.writeValueAsString(response);
        } catch (JsonProcessingException e) {
            logger.error(e.toString());
        }
        return res;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
